package com.bdqn.oauth2gitee.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class MainController {
    @Autowired
    ObjectMapper objectMapper;
    //SpringBoot会自动在方法的参数中注入代表用户的Authentication对象
    @GetMapping("/")
    public String index() {
        return "index.html";
    }

    @GetMapping("/main")
    public void main(@RequestParam(value = "code") String code, HttpServletResponse response) throws IOException {
        Map<String, Object> params = MapUtil.<String, Object>builder().put("grant_type", "authorization_code")
                .put("code", code)
                .put("client_id", "d918b71a58d8c82b7eb0ee6328355acea2eec6c791ca1877a69b0fa945533b27")
                .put("redirect_uri", "http://localhost:8080/main")
                .put("client_secret", "548e322c4ebddf68430d18f1d31c6e27ad36aa75e0c12ebf2037c8ed7d2da056")
                .build();
        String s = HttpUtil.post("https://gitee.com/oauth/token", params);
        HashMap hashMap = objectMapper.readValue(s, HashMap.class);
        String access_token = (String) hashMap.get("access_token");
        System.out.println(access_token);
        // 获取用户信息
        String s2 = HttpUtil.get("https://gitee.com/api/v5/user?access_token=" + access_token);
        System.out.println(s2);
        HashMap hashMap2 = objectMapper.readValue(s2, HashMap.class);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("<h1>登录用户主页</h1>");
        response.getWriter().write("欢迎你，Gitee用户：" + hashMap2.get("name"));
    }
}
